/**
 * Copyright 2008 Mathias Doenitz, http://lis.to/
 *
 * This file is part of the lis.to java desktop client. The lis.to java desktop client is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * The lis.to java desktop client is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with the lis.to java desktop client.
 * If not, see http://www.gnu.org/licenses/
 */

package listo.client.taskfilters;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import listo.client.model.Task;
import listo.client.model.Tasks;
import listo.utils.types.Cal;
import listo.utils.types.DateTime;

@Singleton
public class CompletionFilter extends BaseFilter implements TaskFilter.Listener {

    public enum Mode {
        AllCompleted, TodaysCompleted, NoCompleted
    }

    private Mode mode;
    private Tasks tasks;

    @Inject
    public CompletionFilter(RootFilter rootFilter) {
        rootFilter.addFilterListener(this);
    }

    public Mode getMode() {
        return mode;
    }

    public void setMode(Mode mode) {
        if (mode != this.mode && tasks != null) {
            this.mode = mode;
            update();
        } else {
            this.mode = mode;
        }
    }

    public void tasksChanged(Object updateObject) {
        tasks = (Tasks) updateObject;
        if (mode != null) update();
    }

    private void update() {
        Tasks filteredTasks = new Tasks();
        switch (mode) {

            case AllCompleted:
                filteredTasks = tasks;
                break;

            case TodaysCompleted:
                int today = new Cal().getDateValue();
                for (Task task : tasks) {
                    DateTime lastUpdated = task.getLastUpdated();
                    if (!task.isCompleted() || lastUpdated == null || new Cal(lastUpdated).getDateValue() >= today) {
                        filteredTasks.add(task);
                    }
                }
                break;

            case NoCompleted:
                for (Task task : tasks) {
                    if (!task.isCompleted()) {
                        filteredTasks.add(task);
                    }
                }
                break;
        }
        notifyListeners(filteredTasks);
    }

}